package com.daluzy.chmanager.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.daluzy.chmanager.MyApplication;
import com.daluzy.chmanager.R;
import com.daluzy.chmanager.bean.Record;
import com.daluzy.chmanager.bean.TestPoint;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.List;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;

public class TestPointInfoActivity extends AppCompatActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_area_name)
    TextView tvAreaName;
    @BindView(R.id.tv_test_point_name)
    TextView tvTestPointName;
    @BindView(R.id.tv_test_point_tem)
    TextView tvTestPointTem;
    @BindView(R.id.tv_test_point_person)
    TextView tvTestPointPerson;
    @BindView(R.id.tv_warranty)
    TextView tvWarranty;
    @BindView(R.id.view_bg)
    View viewBg;
    @BindView(R.id.et_new_tem)
    EditText etNewTem;
    @BindView(R.id.tv_update_tem)
    TextView tvUpdateTem;
    @BindView(R.id.rl_bottom)
    RelativeLayout rlBottom;
    private String testPointId;
    private TestPoint testPoint;
    private LoadingDialog loadingDialog;
    private int type = 0;
    private Record record;

    private Handler handler = new Handler(Objects.requireNonNull(Looper.myLooper())) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (type == 1) {
                updateRecord();
                searchData();
            } else {
                initData();
            }
            rlBottom.setVisibility(View.GONE);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_point_info_daluzy);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", 0);
        if (MyApplication.getIntance().getUserType() == 1) {
            tvWarranty.setText("异常报修");
            tvWarranty.setVisibility(View.VISIBLE);
        } else if (MyApplication.getIntance().getUserType() == 2) {
            if (type == 1) {
                tvWarranty.setText("测试维修");
                record = (Record) getIntent().getSerializableExtra("record");
            } else {
                tvWarranty.setText("最新测温提交");
            }
            tvWarranty.setVisibility(View.VISIBLE);
        } else {
            tvWarranty.setVisibility(View.GONE);
        }
        loadingDialog = new LoadingDialog(this);
    }

    private void searchData() {
        if (loadingDialog != null)
            loadingDialog.show();
        BmobQuery<TestPoint> categoryBmobQuery = new BmobQuery<>();
        categoryBmobQuery.addWhereEqualTo("point_name", record.getRecord_test_point());
        categoryBmobQuery.findObjects(new FindListener<TestPoint>() {
            @Override
            public void done(List<TestPoint> object, BmobException e) {
                if (e == null) {
                    if (object != null && object.size() > 0)
                        setData(object.get(0));
                } else {
                    Toast.makeText(TestPointInfoActivity.this, "查询失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
                if (loadingDialog != null)
                    loadingDialog.close();
            }
        });
    }

    private void initData() {
        if (loadingDialog != null)
            loadingDialog.show();
        testPointId = getIntent().getStringExtra("testPointId");
        BmobQuery<TestPoint> bmobQuery = new BmobQuery<TestPoint>();
        bmobQuery.getObject(testPointId, new QueryListener<TestPoint>() {
            @Override
            public void done(TestPoint object, BmobException e) {
                if (e == null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setData(object);
                        }
                    });

                } else {
                    Toast.makeText(TestPointInfoActivity.this, "查询失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
                if (loadingDialog != null)
                    loadingDialog.close();
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.tv_warranty, R.id.view_bg, R.id.tv_update_tem})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.view_bg:
                rlBottom.setVisibility(View.GONE);
                break;
            case R.id.tv_update_tem:
                String tem = etNewTem.getText().toString().trim();
                if (TextUtils.isEmpty(tem)) {
                    Toast.makeText(TestPointInfoActivity.this, "请输入测量温度", Toast.LENGTH_SHORT).show();
                    return;
                }
                updateTestPoint(tem);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_warranty:
                if (MyApplication.getIntance().getUserType() == 1) {
                    Intent intent = new Intent(TestPointInfoActivity.this, AddRecordActivity.class);
                    intent.putExtra("testPoint", testPoint);
                    startActivity(intent);
                } else if (MyApplication.getIntance().getUserType() == 2) {
                    rlBottom.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    private void updateTestPoint(String tem) {
        if (loadingDialog != null)
            loadingDialog.show();
        //更新Person表里面id为6b6c11c537的数据，address内容更新为“北京朝阳”
        testPoint.setPoint_tem(tem);
        testPoint.setTest_person_name(MyApplication.getIntance().getEmployee().getEmployee_name());
        testPoint.setTest_person_id(String.valueOf(MyApplication.getIntance().getEmployee().getEmployee_id()));
        testPoint.update(testPointId, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    handler.sendEmptyMessage(1);

                } else {
                    Toast.makeText(TestPointInfoActivity.this, "查询失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
                if (loadingDialog != null)
                    loadingDialog.close();

            }

        });

    }

    private void updateRecord() {
        if (loadingDialog != null)
            loadingDialog.show();
        //更新Person表里面id为6b6c11c537的数据，address内容更新为“北京朝阳”
        record.setRecord_type("2");
        record.setRecord_employee(MyApplication.getIntance().getEmployee().getEmployee_name());
        record.update(record.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Toast.makeText(TestPointInfoActivity.this, "测试维修完成", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(TestPointInfoActivity.this, "查询失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
                if (loadingDialog != null)
                    loadingDialog.close();
            }

        });
    }

    private void setData(TestPoint testPoint) {
        this.testPoint = testPoint;
        testPointId = testPoint.getObjectId();
        tvAreaName.setText(testPoint.getArea_name());
        tvTestPointName.setText(testPoint.getPoint_name());
        if (TextUtils.isEmpty(testPoint.getTest_person_name())) {
            tvTestPointPerson.setTextColor(getResources().getColor(R.color.Tomato));
            tvTestPointPerson.setText("暂未测试");
        } else {
            tvTestPointPerson.setTextColor(getResources().getColor(R.color.text_color));
            tvTestPointPerson.setText(testPoint.getTest_person_name());
        }
        if (TextUtils.isEmpty(testPoint.getPoint_tem()))
            tvTestPointTem.setText("暂未测试");
        else tvTestPointTem.setText(testPoint.getPoint_tem());
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (type == 1)
            searchData();
        else
            initData();
    }
}
